package com.rdc.dictionary.search;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rdc.dictionary.R;
import com.rdc.dictionary.adapter.WordsAdapter;
import com.rdc.dictionary.application.App;
import com.rdc.dictionary.bean.Word;
import com.rdc.dictionary.bean.WordSearch;
import com.rdc.dictionary.mvpPresenters.BasePresenter;
import com.rdc.dictionary.util.DataBase;
import com.rdc.dictionary.util.NetworkUtil;
import com.rdc.dictionary.util.WordsAction;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.List;

/**
 * @author Soul Mate
 * @file 文件名
 * @brief 搜索翻译presenter
 */

public class SearchPresenter extends BasePresenter<SearchActivityContact.IMainView>
		implements SearchActivityContact.IMainPresenter ,SearchActivityContact.SearchCallback
{

	private SearchActivityContact.IMainView mView;

	private SearchModel mModel=new SearchModel();

	//对单词的操作管理类
	private WordsAction mWordsAction = WordsAction.getInstance(App.sContext);



//在view层里记得初始化
	@Override public void init()
	{
		mView = getMvpView();

	}

	@Override public void searchWord(String address)
	{
		//检查网络
		if(NetworkUtil.isMobileDataEnable(App.sContext))
		{
			//网络请求
			mModel.loadWord(address);
			Toast.makeText(App.sContext , "搜索中请稍等", Toast.LENGTH_SHORT).show();

			//搜索成功自动显示的回调
			mModel.setListener(this);
		}else
		{
			//无网络
			Toast.makeText(App.sContext , "获取失败，请检查网络", Toast.LENGTH_SHORT).show();
		}

	}


	/**
	 * @param s 英式或美式发音
	 */
	@Override public void playMP3(String s)
	{

		//判断网络地址还是本地地址
		if(mModel.getTmpWord().getEnglishVoice().charAt(0) == 'h')
		{
			//判断播放什么口音
			if (s == "E")
				mWordsAction.playOnlineMP3(mModel.getTmpWord().getEnglishVoice(), App.sContext);
			else
				mWordsAction.playOnlineMP3(mModel.getTmpWord().getAmericanVoice(), App.sContext);
		}else
		{
       		mWordsAction.playLocalMP3(mModel.getTmpWord().getWord(),s,App.sContext);
		}

	}

	/**
	 * 从数据库获取信息后更新model数据
	 * @param word 从数据库中获取的Word生词
	 */
	@Override public void updateModel(Word word)
	{
		mModel.setTmpWord(word);
	}


	/**
	 * 检查是否重复添加生词
	 */
	@Override public boolean checkRepetition()
	{
		return DataBase.check(mModel.getTmpWord());
	}



	/**
	 * 保存mp3到本地
	 */
	@Override public void saveMP3()
	{
		 mWordsAction.saveWordMP3(mModel.getTmpWord());
	}


	/**
	 * 保存搜索记录到数据库
	 */
	@Override public void saveSearch(String  search)
	{
		DataBase.saveWordSearchList(search);
	}

	/**
	* 保存生词到数据库
	*/
	public void saveWordTODataBase()
	{

		DataBase.saveNewWord(mModel.getTmpWord());

	}


	//数据获取成功的回调方法
	@Override public void onSucc(Word w)
	{
		mView.show(w);

	}

	@Override public void onFail()
	{
		Toast.makeText(App.sContext , "获取失败，请检查网络", Toast.LENGTH_SHORT).show();
	}
}
